import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yn_goods/config/app_color.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/widgets/appbar/common_app_bar.dart';
import 'package:flutter_yn_goods/widgets/button/common_button.dart';
import 'package:flutter_yn_goods/widgets/image/image_view.dart';
import 'package:flutter_yn_goods/widgets/widget_line.dart';
import 'package:get/get.dart';

import 'order_review_logic.dart';

class OrderReviewPage extends StatelessWidget {
  final OrderReviewLogic logic = Get.put(OrderReviewLogic());

  OrderReviewPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.colorF5F5F5,
      appBar: CommonAppBar(
        title: LocaleKeys.order_review.tr,
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildProductInfo(),
            SizedBox(height: 10.h),
            _buildRatingSection(),
            SizedBox(height: 10.h),
            _buildReviewContent(),
            SizedBox(height: 20.h),
            _buildSubmitButton(),
          ],
        ),
      ),
    );
  }

  // 商品信息区域
  Widget _buildProductInfo() {
    return Container(
      margin: EdgeInsets.all(16.w),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 商品图片
          ClipRRect(
            borderRadius: BorderRadius.circular(6.w),
            child: ImageView(
              imageUrl: logic.order.image,
              width: 80.w,
              height: 80.w,
              fit: BoxFit.cover,
            ),
          ),
          SizedBox(width: 12.w),
          // 商品信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  logic.order.storeName ?? '',
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                    color: AppColor.color202020,
                  ),
                ),
                SizedBox(height: 8.h),
                Text(
                  '¥${logic.order.totalPrice ?? '0.00'}',
                  style: TextStyle(
                    fontSize: 15.sp,
                    fontWeight: FontWeight.bold,
                    color: AppColor.primary,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 评分区域
  Widget _buildRatingSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 商品评分
          Row(
            children: [
              Text(
                '${LocaleKeys.product_rating.tr}:',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: AppColor.color202020,
                ),
              ),
              SizedBox(width: 16.w),
              Obx(() => _buildRatingStars(
                    rating: logic.productRating.value,
                    onRatingChanged: (rating) {
                      logic.productRating.value = rating;
                    },
                  )),
            ],
          ),
          SizedBox(height: 16.h),
          const WidgetLine(),
          SizedBox(height: 16.h),
          // 服务评分
          Row(
            children: [
              Text(
                '${LocaleKeys.service_rating.tr}:',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: AppColor.color202020,
                ),
              ),
              SizedBox(width: 16.w),
              Obx(() => _buildRatingStars(
                    rating: logic.serviceRating.value,
                    onRatingChanged: (rating) {
                      logic.serviceRating.value = rating;
                    },
                  )),
            ],
          ),
        ],
      ),
    );
  }

  // 评价内容区域
  Widget _buildReviewContent() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            LocaleKeys.review_content.tr,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
              color: AppColor.color202020,
            ),
          ),
          SizedBox(height: 12.h),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w),
            decoration: BoxDecoration(
              color: AppColor.colorF5F5F5,
              borderRadius: BorderRadius.circular(8.w),
            ),
            child: TextField(
              controller: logic.reviewController,
              maxLines: 5,
              style: TextStyle(
                fontSize: 14.sp,
                color: AppColor.color202020,
              ),
              decoration: InputDecoration(
                hintText: LocaleKeys.enter_review.tr,
                hintStyle: TextStyle(
                  fontSize: 14.sp,
                  color: AppColor.color999999,
                ),
                border: InputBorder.none,
              ),
            ),
          ),

          SizedBox(height: 16.h),

          // 上传图片区域
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "上传图片",
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: AppColor.color202020,
                ),
              ),
              SizedBox(height: 12.h),
              Obx(() => _buildImagePreview()),
            ],
          ),
        ],
      ),
    );
  }

  // 图片预览和上传
  Widget _buildImagePreview() {
    return Container(
      width: double.infinity,
      child: Wrap(
        spacing: 12.w,
        runSpacing: 12.w,
        children: [
          // 已选择的图片预览
          ...List.generate(
            logic.selectedImages.length,
            (index) => _buildImageItem(index),
          ),

          // 添加图片按钮
          if (logic.selectedImages.length < 5)
            GestureDetector(
              onTap: () => logic.pickImages(),
              child: Container(
                width: 80.w,
                height: 80.w,
                decoration: BoxDecoration(
                  color: AppColor.colorF5F5F5,
                  borderRadius: BorderRadius.circular(8.w),
                  border: Border.all(
                    color: AppColor.colorE5E5E5,
                    width: 1,
                  ),
                ),
                child: Icon(
                  Icons.add_photo_alternate_outlined,
                  color: AppColor.color999999,
                  size: 30.w,
                ),
              ),
            ),
        ],
      ),
    );
  }

  // 单个图片预览项
  Widget _buildImageItem(int index) {
    return Stack(
      children: [
        FutureBuilder<Uint8List?>(
          future: logic.selectedImages[index].thumbnailData,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done &&
                snapshot.data != null) {
              return Container(
                width: 80.w,
                height: 80.w,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.w),
                  image: DecorationImage(
                    image: MemoryImage(snapshot.data!),
                    fit: BoxFit.cover,
                  ),
                ),
              );
            }
            return Container(
              width: 80.w,
              height: 80.w,
              decoration: BoxDecoration(
                color: AppColor.colorF5F5F5,
                borderRadius: BorderRadius.circular(8.w),
              ),
              child: Center(
                child: CircularProgressIndicator(
                  strokeWidth: 2.w,
                  valueColor: AlwaysStoppedAnimation<Color>(AppColor.primary),
                ),
              ),
            );
          },
        ),
        // 删除按钮
        Positioned(
          top: 0,
          right: 0,
          child: GestureDetector(
            onTap: () => logic.removeImage(index),
            child: Container(
              padding: EdgeInsets.all(4.w),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.5),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.close,
                color: Colors.white,
                size: 14.w,
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 提交按钮
  Widget _buildSubmitButton() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: CommonButton.expend(
        title: LocaleKeys.submit_review.tr,
        height: 44.h,
        // loading: logic.isSubmitting.value,
        onClick: () async {
          if (logic.isSubmitting.value) return;
          final success = await logic.submitReview();
          if (success) {
            Get.back(result: true);
          }
        },
      ),
    );
  }

  // 评分星星
  Widget _buildRatingStars({
    required int rating,
    required Function(int) onRatingChanged,
  }) {
    return Row(
      children: List.generate(5, (index) {
        return GestureDetector(
          onTap: () => onRatingChanged(index + 1),
          child: Icon(
            index < rating ? Icons.star : Icons.star_border,
            color: index < rating ? Colors.amber : AppColor.color999999,
            size: 24.w,
          ),
        );
      }),
    );
  }
}
